package org.example.server;

import com.alipay.remoting.exception.CodecException;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.datagram.DatagramSocketOptions;
import org.example.command.OrderCmd;
import org.example.order.CmdPack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
public class EngineServer {

    @Value("${server.engine.ip}")
    private String ip;

    @Value("${server.engine.port}")
    private int port;

    @Autowired
    PacketNoService packetNoService;

    private DatagramSocket udp;


    /**
     * UDP服务，为撮合服务提供
     */
    @PostConstruct
    public void init() {
        Vertx vertx = Vertx.vertx();
        udp = vertx.createDatagramSocket(new DatagramSocketOptions());

    }

    public void send(List<OrderCmd> allCmds) throws CodecException {
        CmdPack cmdPack = new CmdPack(packetNoService.nextNo(),allCmds);
        Buffer content = Buffer.buffer(cmdPack.serialize());
        udp.send(content,port,ip)
                .onComplete(asyncResult -> {
                    System.out.println("发送成功" + asyncResult.succeeded());
                });
    }
}
